package com.jmlee.controller;

import com.jmlee.bo.SecKillOrderBO;
import com.jmlee.cache.SecKillCache;
import com.jmlee.pojo.CommonResult;
import com.jmlee.pojo.SecKillItems;
import com.jmlee.service.SecKillService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.List;

/**
 * @Description 秒杀服务接口
 * @Author jmLee
 * @Date 2021/3/11 21:20
 * @Version 1.0
 */
@RestController
@RequestMapping("/seckill")
public class SecKillController {

    private static final Logger LOGGER = LoggerFactory.getLogger(com.jmlee.controller.SecKillController.class);


    // 本地内存标识，用来指示商品是否已售完
//    private static ConcurrentHashMap<Long, Boolean> itemSoldOutMap = new ConcurrentHashMap<>();

    @Autowired
    private SecKillService seckillService;

    @Autowired
    private SecKillCache secKillCache;


    @PostMapping("/create")
    public CommonResult secKill(@RequestBody SecKillOrderBO secKillOrderBO) {

        // 先去本地内存标记中判断商品是否售完
//        if(itemSoldOutMap.get(secKillOrderBO.getItemId()) != null) {
//            return CommonResult.failed("商品已售空，欢迎下次光临");
//        }


        // 判断商品是否过期(避免页面未及时刷新导致商品信息是过期信息)
        if(!secKillCache.hasStock(secKillOrderBO.getItemId())) {
            return CommonResult.expired("商品已过期");
        }

        // 判断用户是否已抢过商品
        if(secKillCache.isOrderExist(secKillOrderBO.getUserId(),secKillOrderBO.getItemId())){
            return CommonResult.failed("您已购买本商品，不能重复购买");
        }


        // 预减Redis中的库存，返回剩余库存
        Long restStock = secKillCache.deduceStock(secKillOrderBO.getItemId());

        LOGGER.info("剩余库存:" + restStock);
        if(restStock < 0) {
//            itemSoldOutMap.put(secKillOrderBO.getItemId(), true);
            secKillCache.incrementStock(secKillOrderBO.getItemId());
            return CommonResult.failed("商品已售空，欢迎下次光临");
        }
        try {

            // 后续下单处理
            seckillService.doSecKill(secKillOrderBO);

        } catch (Exception e) {
            // 后台数据库扣减库存发生异常,还原库存和标识
            secKillCache.incrementStock(secKillOrderBO.getItemId());
//            if(itemSoldOutMap.get(secKillOrderBO.getItemId()) != null) {
//                itemSoldOutMap.remove(secKillOrderBO.getItemId());
//            }
            LOGGER.error("创建订单失败", e);
            return CommonResult.failed("创建订单失败:" + e.getMessage());

        }
        return CommonResult.success("抢单成功");
    }


    @GetMapping("/item")
    public CommonResult getSecKillItem() {

        List<SecKillItems> itemInfo = seckillService.getItemInfo();

        if(itemInfo.isEmpty() || itemInfo == null) {
            return CommonResult.failed();
        }
        return CommonResult.success(itemInfo);
    }
}
